# -*- coding: UTF-8 -*-
# 2023/11/26 23:41
import os
from tkinter import filedialog

from ttkbootstrap import Toplevel, Frame, Button, Label, IntVar
from ttkbootstrap.tooltip import ToolTip

from computer.class_page_frame import class_page_frame
from computer.computer_tools import get_page_img
from tools.get_configer import my_configer
from tools.get_icon import last_page, skip_page, next_page, confirm, select_all, set_save_path
from tools.get_logger import get_logger
from tools.img_tool import set_pil_img
from tools.input_validation import int_placeholder_Entry
from tools.pool_download_image import pool_download_image

configer = my_configer()
loger = get_logger()


class computer_class_page(Toplevel):
    """
    指定分类下载弹出窗口
    """

    def __init__(self, event, master, title, *args, **kwargs):
        """
        根据传入的btn和master生成分类图片展示窗口
        :param btn: 选择的class信息,btn本身可以通过以下方式获取分类信息
            getattr(btn, "btn_img_id")
            getattr(btn, "btn_img_url")
            getattr(btn, "btn_name")
            getattr(btn, "btn_cover_save_path")
        :param master: 分类下图片窗口父对象
        :param args: Toplevel参数
        :param kwargs: Toplevel参数
        """

        super().__init__(master=master, title=title, *args, **kwargs)
        self.master = event.widget
        self.class_id = getattr(self.master, "btn_img_id")
        self.class_name = getattr(self.master, "btn_name")
        self.page_no = IntVar(self, 0)  # 每页100张最大74
        self.page_sum = 100
        loger.info(f"打开了[{self.class_name}]窗口, 分类ID:{self.class_id}")

        self.Toplevel_init()
        self.setupUI()
        self.setlayout()
        self.setCallback()
        self.setBalloon()

        loger.info(f"初始化分类窗口,分类:{self.class_name}")

    def Toplevel_init(self):
        self.grab_set()  # 设置为模态窗口
        # self.place_window_center()  # 居中

        self.minsize(1500, 900)

    def setupUI(self):
        # 空间布局组件
        self.class_frame = Frame(self)
        self.download_info_frame = Frame(self.class_frame)

        # 操作按钮___________________________________________________________________________________
        # 上一页
        self.last_but_img = set_pil_img(last_page, (50, 50))
        self.last_but = Button(self.download_info_frame, text="上一页", image=self.last_but_img, compound='bottom')
        # 下一页
        self.next_but_img = set_pil_img(next_page, (50, 50))
        self.next_but = Button(self.download_info_frame, text="下一页", image=self.next_but_img, compound='bottom')

        # 指定分页
        self.skip_page_button_img = set_pil_img(skip_page, (50, 50))
        self.skip_page_button = Button(self.download_info_frame, text="跳转至", image=self.skip_page_button_img, compound='bottom')
        self.skip_page_entry = int_placeholder_Entry(self.download_info_frame, placeholder="在此填写跳转分页", textvariable=self.page_no, width=6)

        # 确认下载按钮
        self.confirm_download_button_img = set_pil_img(confirm, (50, 50))
        self.confirm_download_button = Button(self.download_info_frame, text="确认下载", image=self.confirm_download_button_img, compound='bottom')

        # 本页全下载
        self.select_all_btn_img = set_pil_img(select_all, (50, 50))
        self.select_all_btn = Button(self.download_info_frame, text="本页全部下载", image=self.select_all_btn_img, compound='bottom')

        # 保存至
        self.save_path = os.path.abspath('./')
        self.save_to_button_img = set_pil_img(set_save_path, (50, 50))
        self.save_to_button = Button(self.download_info_frame, text="保存至", image=self.save_to_button_img, compound='bottom')
        self.save_to_label = Label(self.download_info_frame, text=self.save_path)

        # 预览空间___________________________________________________________________________________
        self.class_page_frame = class_page_frame(line_num=5,
                                                 img_url_save_path_list=get_page_img(self.class_id, self.page_no.get(), self.page_sum),
                                                 master=self.class_frame)

    def setlayout(self):
        # 几个主空间布局
        self.class_frame.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.download_info_frame.place(relx=0, rely=0, relwidth=1, relheight=0.1)
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        # 按钮布局
        self.last_but.pack(side="left", padx=15)
        self.next_but.pack(side="left", padx=15)
        self.skip_page_button.pack(side="left", padx=3)
        self.skip_page_entry.pack(side="left", padx=3)
        self.confirm_download_button.pack(side="left", padx=15)
        self.select_all_btn.pack(side="left", padx=15)
        self.save_to_button.pack(side="left", padx=3)
        self.save_to_label.pack(side="left", padx=3)

    def setCallback(self):
        self.next_but.config(command=self.display_next_page)
        self.last_but.config(command=self.display_last_page)
        self.skip_page_button.config(command=self.skip_specify_page)
        self.confirm_download_button.config(command=self.confirm_download_button_callback)
        self.select_all_btn.config(command=self.select_all_callback)
        self.save_to_button.config(command=self.get_save_to_path)

    def setBalloon(self):
        ToolTip(self.skip_page_entry, "设置指定跳转页码")

    def get_save_to_path(self):
        save_path = filedialog.askdirectory(initialdir="./",
                                            parent=self,
                                            title="选择保存目录")

        if save_path in ["", None]:
            loger.info(f"未选择目录,忽略")
            return
        else:
            self.save_path = save_path
            self.save_to_label.config(text=save_path)

    def display_next_page(self):
        self.page_no.set(self.page_no.get() + 1)
        next_class_page_frame = class_page_frame(line_num=5,
                                                 img_url_save_path_list=get_page_img(self.class_id, self.page_no.get(), self.page_sum),
                                                 master=self.class_frame)

        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = next_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def display_last_page(self):
        self.page_no.set(self.page_no.get() - 1)
        last_class_page_frame = class_page_frame(line_num=5,
                                                 img_url_save_path_list=get_page_img(self.class_id, self.page_no.get(), self.page_sum),
                                                 master=self.class_frame)
        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = last_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def skip_specify_page(self):
        last_class_page_frame = class_page_frame(line_num=5,
                                                 img_url_save_path_list=get_page_img(self.class_id, self.page_no.get(), self.page_sum),
                                                 master=self.class_frame)

        self.class_page_frame.place_forget()
        self.class_page_frame.destroy()
        self.class_page_frame = last_class_page_frame
        self.class_page_frame.place(relx=0, rely=0.1, relwidth=1, relheight=0.9)

        self.update()

    def confirm_download_button_callback(self):
        """
        确认下载回调
        """
        loger.info(f"发起选择下载")
        tag_id_keys_urls_dict_list = self.class_page_frame.get_select_btn()

        self.submit_download(tag_id_keys_urls_dict_list)

    def select_all_callback(self):
        """
        全选回调
        """
        loger.info(f"分类详情页批量提交本页全部下载")
        tag_id_keys_urls_dict_list = self.class_page_frame.get_all_btn()

        self.submit_download(tag_id_keys_urls_dict_list)

    def submit_download(self, tag_id_keys_urls_dict_list):
        """
        遍历所有提交下载
        :param tag_id_keys_urls_dict_list:
        [
            {
                "img_tag": f"{img_info['utag']}_{img_info['class_id']}_{img_info['id']}".replace(" ", "_"),
                "img_id": f"{img_info['class_id']}_{img_info['id']}",
                "url_key_list":["img_1600_900",...],
                "img_url": {
                    f"img_{img_info['resolution']}": img_info["url"],
                    "img_1600_900": img_info["img_1600_900"],
                    "img_1440_900": img_info["img_1440_900"],
                    "img_1366_768": img_info["img_1366_768"],
                    "img_1280_800": img_info["img_1280_800"],
                    "img_1280_1024": img_info["img_1280_1024"],
                    "img_1024_768": img_info["img_1024_768"]
            }
            ....
        ]
        """
        # 判断保存目录
        class_save_path = os.path.join(self.save_path, self.class_name)
        if not os.path.exists(class_save_path):
            os.mkdir(class_save_path)

        # 获取所有分类的对应图片地址
        all_download_list = list()
        for tag_id_key_urls_dict in tag_id_keys_urls_dict_list:
            _img_tag = tag_id_key_urls_dict["img_tag"]
            _img_id = tag_id_key_urls_dict["img_id"]

            _max_img_size = tag_id_key_urls_dict["url_key_list"][0]
            _max_img_url = tag_id_key_urls_dict["img_url"][_max_img_size]

            _img_name = f"{_img_tag}_{_max_img_size}.jpg"  # tag里面已经有classid和图id
            _save_path = os.path.abspath(os.path.join(self.save_path, self.class_name, _img_name))

            all_download_list.append([_save_path, _max_img_url])

            loger.info(f"解析下载保存地址:{_max_img_url}, 图片url:{_save_path}")

        # 提交下载
        pool_download_image(all_download_list)
